判断一个变量类型是数组还是对象

var arr=[1];
var json={age:18}

数组或者对象的typeof 值都是object。

一、通过length

一般情况下对象没有length属性值,其值为undefiend,而数组的length值为number类型。
缺点:非常不实用,当对象的属性存在length,且其值为number(比如类数组),则该方法失效,不建议使用,看看即可。

二、验证构造函数

1.instanceof :判断一个实例是否由构造函数(Array)创建出来

console.log(arr instanceof Array);//true
console.log(json instanceof Array);//false

2.对象的constructor属性用于返回创建该对象的构造函数。

console.log(arr.constructor===Array);//true
console.log(json.constructor===Array);//false

这种方法有2个问题,
一、就是验证不够严格。 即使对象创建时不是使用数组创建的,但是只要原型链上有数组类型,也认为是数组,如下面一段代码:

function Test(){}
Test.prototype = Array.prototype;
let test = new Test();
console.log(test instanceof Array);//true
console.log(test.constructor===Array);//true

二、instanceof 和constructor 判断的变量,必须在当前页面声明的,比如,一个页面(父页面)有一个iframe,iframe中引用了一个页面(子页面),在子页面中声明了一个a,并将其赋值给父页面的一个变量arr,这时判断该变量, arr.constructor===Array 或arr instanceof Array都会返回false;
原因:

1、array属于引用型数据,在传递过程中,仅仅是引用地址的传递。
2、每个页面的Array原生对象所引用的地址是不一样的,在子页面声明的array,所对应的构造函数,是子页面的Array对象;父页面来进行判断,使用的Array并不等于子页面的Array;

三、toString()方法

该方法原理

 console.log(Object.prototype.toString.call(arr) === '[object Array]'); //true
console.log(Object.prototype.toString.call(json) === '[object Array]'); //false
四、数组仅有的方法
console.log(arr.sort === Array.prototype.sort); //true
 console.log(json.sort === Array.prototype.sort); //false
五、Array.isArray()
Array.isArray(arr);  // true
Array.isArray(obj); //false
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值